<template>
  <div class="page-container" >
    <router-view v-if="$route.name !== 'MeetingOverList'"></router-view>
    <div v-else>
      <!-- 顶部标题栏 -->
      <header class="header">
        <BackBtn />
        <h1>结束的会议</h1>
        <Time />
      </header>

      <!-- 主要内容区域 -->
      <div class="main-content" style="margin-top: 120px;">
        <!-- 搜索和筛选区域 -->
        <div class="search-section">
          <el-input v-model="searchText" placeholder="支持搜索会议题目" class="search-input">
            <template #append>
              <el-button type="danger" class="search-btn" @click="handleSearch">
                <el-icon class="search-icon">
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>

          <div class="filter-section">
            <!-- 日期范围选择 -->
            <div class="date-range-picker">
              <el-date-picker v-model="dateRange[0]" type="date" placeholder="开始日期" class="date-picker"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="handleFilterChange" />
              <span class="separator">—</span>
              <el-date-picker v-model="dateRange[1]" type="date" placeholder="结束日期" class="date-picker"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="handleFilterChange" />
            </div>

            <!-- 排序选择 -->
            <el-select v-model="sortBy" placeholder="排序：发起日期(倒序)" @change="handleFilterChange">
              <el-option label="发起日期(倒序)" value="desc" />
              <el-option label="发起日期(正序)" value="asc" />
              <el-option label="签到日期(倒序)" value="desc1" />
              <el-option label="签到日期(正序)" value="asc1" />
            </el-select>

            <!-- 状态筛选 -->
            <el-select v-model="status" placeholder="状态筛选：全部" @change="handleFilterChange">
              <el-option label="状态筛选：全部" value="all" />
              <el-option label="已签齐" value="signed" />
              <el-option label="未签齐" value="unsigned" />
            </el-select>

            <!-- 导出按钮 -->
            <el-button type="danger" @click="handleExport" class="export-btn" :loading="isExporting" style="width: 180px;background-color: #c62828;border: none;margin-left: 150px;">导出列表</el-button>
          </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-section" v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(0,0,0,0)">
          <div class="meeting-list">
            <!-- 表头 -->
            <div class="meeting-header">
              <div class="header-item title">会议题目</div>
              <div class="header-item status">签到状态</div>
              <div class="header-item sign-date">签到时间</div>
              <div class="header-item create-date" style="margin-left: 40px;">发起日期</div>
              <div class="header-item actions"></div>
            </div>

            <!-- 数据列表 -->
            <div v-for="(item, index) in endedMeetings" :key="index" class="meeting-item">
              <div class="red-line"></div>
              <div class="meeting-info">
                <div class="info-title">{{ item.title }}</div>
                <div class="info-status" :style="{ color: getStatusColor(item.signStatus) }">
                  {{ item.signStatus }}
                  <el-button class="showOverMeeting" @click="handleDetail(item)">
                    签到情况
                  </el-button>
                </div>
                <div class="info-sign-date">{{ item.startTime }}至{{ item.endTime }}</div>
                <div class="info-create-date" style="margin-left: 35px;">{{ item.createdAt }}</div>
                <div class="info-actions">
                  <el-button type="primary" @click="handleMDetail(item)">详情</el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-section">
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
              :background="false" layout="prev, pager, next, jumper" :total="endedTotal" @size-change="onSizeChange"
              @current-change="onCurrentChange" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useMeetingsStore } from '@/stores/meetings'
import { storeToRefs } from 'pinia'
import { exportMeetings } from '@/api/meetings'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'

const router = useRouter()
const meetingsStore = useMeetingsStore()
const {
  endedMeetings,
  endedTotal,
  pageNum,
  pageSize,
  dateRange,
  sortBy,
  loading,
  searchText,
  status
} = storeToRefs(meetingsStore)

const isExporting = ref(false) // 添加导出状态



// 获取已结束会议列表数据
const fetchEndedMeetingList = () => {
  meetingsStore.fetchEndedMeetings()
}

// 处理搜索
const handleSearch = () => {
  pageNum.value = 1
  fetchEndedMeetingList()
}

// 处理筛选条件变化
const handleFilterChange = () => {
  pageNum.value = 1
  fetchEndedMeetingList()
}

// 分页大小改变
const onSizeChange = (val) => {
  pageSize.value = val
  fetchEndedMeetingList()
}

// 页码改变
const onCurrentChange = (val) => {
  pageNum.value = val
  fetchEndedMeetingList()
}

// 查看签到情况
const handleDetail = (row) => {
  router.push(`/meeting/sign/${row.mid}`)
  
}

// 查看详情
const handleMDetail = (row) => {
  router.push({
    path: `/meeting/detail/${row.mid}`,
    query: { from: 'ended' }  // 添加来源标识
  })
}


// 导出列表
const handleExport = async () => {
  isExporting.value = true; // 开始导出时设置为加载状态
  try {
    // 添加参数检查日志
    console.log('导出参数:', {
      sortBy: sortBy.value,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
      searchText: searchText.value,
      status: status.value,
    });

    const response = await exportMeetings(
      sortBy.value,
      dateRange.value[0],
      dateRange.value[1],
      searchText.value,
      status.value === 'all' ? '' : status.value,
    );

    // 调试信息
    console.log('Response headers:', response.headers);
    console.log('Response type:', response.type);
    console.log('Response size:', response.size);

    // 检查响应是否为空
    if (!response || response.size === 0) {
      throw new Error('导出的文件为空');
    }

    // 检查响应类型
    const contentType = response.type;
    if (!contentType.includes('spreadsheetml.sheet')) {
      // 如果响应不是Excel文件，尝试读取错误信息
      const text = await response.text();
      throw new Error(text || '导出的文件格式不正确');
    }

    // 创建下载链接
    const blob = new Blob([response], { type: contentType });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = `会议列表_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(link);
    link.click();

    // 清理资源
    window.URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('Export error:', error);
    ElMessage.error(error.message || '导出失败');
  } finally {
    isExporting.value = false; // 导出完成后重置加载状态
  }
}

// 添加一个方法来获取状态颜色
const getStatusColor = (status) => {
    switch (status) {
        case '已签齐':
            return 'green';
        case '未签齐':
            return 'red';
        case '无参会人':
            return 'gray';
    }
}
// 重置所有筛选条件的函数
const resetFilters = () => {
    searchText.value = ''  // 重置搜索文本
    dateRange.value = [null, null]  // 重置日期范围
    status.value = 'all'  // 重置状态筛选
    sortBy.value = 'desc'  // 重置时间排序为默认的倒序
    pageNum.value = 1  // 重置页码
}


onMounted(() => {
  resetFilters()  // 初始化重置
  loading.value = true
  fetchEndedMeetingList()
  loading.value = false
})

// 添加组件卸载钩子
onUnmounted(() => {
  pageNum.value = 1  // 组件卸载时重置页码
})
</script>

<style scoped>
@import '@/assets/css/meeting/list.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/select.css';
.search-section {
    /* background: white; */
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 10px;
    /* box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1); */
    margin-left: 105px;
    min-width: 900px;
    width: 84%;
  }
  
  /* 搜索框特定样式 */
  .search-input {
    margin-bottom: 20px;
  }
  
  .search-input :deep(.el-input__wrapper) {
    height: 40px !important;
    border-radius: 8px 0 0 8px !important;
    padding: 0 12px !important;
    box-sizing: border-box;
  }
  
  .search-input :deep(.el-input:hover .el-input__wrapper) {
    box-shadow: 0 0 0 1px #c62828 inset !important;
  }
  
  .search-input :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #c62828 inset !important;
  }
  
  .search-input :deep(.el-input-group__append) {
    padding: 0 !important;
    border: none !important;
    background: none !important;
  }
  
  /* 搜索按钮样式 */
  .search-btn {
    background-color: #c62828 !important;
    border: none;
    height: 40px;
    width: 180px;
    color: white;
    padding: 5px 10px;
    border-radius: 0 8px 8px 0 !important;
    cursor: pointer;
  }
  
  .search-btn:hover {
    background-color: #a91919 !important;
  }
  
  .search-btn .el-icon {
    font-size: 20px;
    color: white;
  }

</style>